package com.xtx.json;

import java.util.Collection;
import java.util.Map;

/**
 * @author Chenin
 * @version 2007-1-17
 */
@SuppressWarnings("unchecked")
public class JsonPrinter {
    /**
     * Produce a string in double quotes with backslash sequences in all the
     * right places.
     */
    protected static String toQuote(String value) {
        if (value == null || value.length() == 0) {
            return "''";
        }
        StringBuffer strb = new StringBuffer();
        strb.append("'");
        int size = value.length();
        char pre = 0;
        char chr = 0;
        for (int i = 0; i < size; i++) {
            pre = chr;
            chr = value.charAt(i);
            switch (chr) {
                case '\'':
                case '\\':
                    strb.append('\\');
                    strb.append(chr);
                    break;
                case '/':
                    if (pre == '<') {
                        strb.append('\\');
                    }
                    strb.append(chr);
                    break;
                case '\b':
                    strb.append("\\b");
                    break;
                case '\f':
                    strb.append("\\f");
                    break;
                case '\n':
                    strb.append("\\n");
                    break;
                case '\r':
                    strb.append("\\r");
                    break;
                case '\t':
                    strb.append("\\t");
                    break;
                default:
                    strb.append(chr);
                    break;
            }
        }
        strb.append("'");
        return strb.toString();
    }

    /**
     * Make a JSON text of an Object value.
     */
    protected static String getString(Object value) {
        if (value == null) {
            return "null";
        }
        if (value instanceof Number || value instanceof Boolean || value instanceof JsonScript) {
            return value.toString();
        }
        if (value instanceof JsonEntity) {
            return ((JsonEntity) value).toJsonString();
        }
        if (value instanceof Map) {
            return new JsonObject((Map) value).toJsonString();
        }
        if (value instanceof Collection) {
            return new JsonArray((Collection) value).toJsonString();
        }
        return JsonPrinter.toQuote(value.toString());
    }
}
